var mongoose = require('mongoose');
var mongooseValidateFilter = require('mongoose-validatefilter');

var validate = new mongooseValidateFilter.validate();
var filter = new mongooseValidateFilter.filter();

var UsersSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    name: {
        first: String,
        last: String
    },
    email: {
        type: String
    },
    date: {
        type: Date,
        default: Date.now
    },
    salt: {
        type: Boolean,
        default: true
    },
    vip: {
        type: Boolean,
        default: false
    },
    last_login: {
        type: Date,
        default: Date.now
    }
});

UsersSchema.virtual('name.full').get(function() {
    return this.name.first + ' ' + this.name.last;
});

UsersSchema.virtual('name.full').set(function(name) {
    var split = name.split(' ');
    this.name.first = split[0];
    this.name.last = split[1];
});

// 密码加密
UsersSchema.statics.crypto = function(s) {
    var crypto = require('crypto');
    var hash = crypto.createHash('sha1');

    // 加盐
    for (var i = 0; i < 1000; i++) {
        hash.update(new Buffer(s + i, "binary"));
    };

    return hash.digest('hex');
};

UsersSchema.statics.findByUserName = function(username, callback) {
    return this.findOne({
        username: String(username).trim().toLowerCase()
    }, callback);

}

UsersSchema.statics.authenticate = function(u, callback) {
    var $this = this;
    var u = u || {
        username: '',
        password: ''
    };
    $this.findByUserName(u.username, function(err, user) {
        if(err || !user){
            err = true;
        }
        return callback(err, user);

    });

}

UsersSchema.statics.findByEmail = function(email, callback) {
    return this.findOne({
        email: email
    }, callback);
}



// username

validate.add('username', {
    required: true,
    msg: '用户名不能为空！',
});

validate.add('username', {
    type: 'string',
    msg: '用户名必须为字符串！',
});

validate.add('username', {
    minLength: 4,
    msg: '用户名最少4位！',
});

validate.add('username', {
    maxLength: 16,
    msg: '用户名最多16位！',
});

validate.add('username', {
    callback: function(username, respond) {
        // 这里有3个判断值，分别为：
        // __isCreate: 执行 cretaOne 时为真
        // __isUpdate: 执行 updateOne 时为真
        // __isRemove: 执行 removeOne 时为真

        if (this.__isCreate) {
            this.model('User').findOne({
                username: username.trim().toLowerCase(),
            }, function(err, user) {

                if (err || user) {
                    return respond(false);

                } else {
                    return respond(true);

                }


            });
        } else {
            return respond(true);
        }
    },
    msg: '用户名已被占用！'
});



filter.add('username', 'trim');
filter.add('username', 'lowercase');

filter.add('password', function(password, respond) {
    return respond(this.crypto(password));
});



// name

validate.add('name', {
    exist: true,
    type: 'string',
    msg: '姓名必须为字符串！',
});

validate.add('name', {
    exist: true,
    trim: true,
    minLength: 2,
    msg: '姓名至少为2位！',
});

validate.add('name', {
    exist: true,
    trim: true,
    maxLength: 12,
    msg: '姓名最多为12位！',
});

filter.add('name', 'trim');


// email

validate.add('email', {
    exist: true,
    type: 'string',
    msg: '邮箱必须为字符串格式！',
});

validate.add('email', {
    exist: true,
    type: 'email',
    msg: '邮箱格式不正确！',
});

validate.add('email', {
    exist: true,
    maxLength: 120,
    msg: '邮箱长度不能超过120个字符！',
});

validate.add('email', {
    callback: function(value, respond) {
        value = String(value).trim().toLowerCase();
        if (this.__isCreate) {
            this.model('User').findByEmail(value, function(err, user) {
                if (err || user) {
                    return respond(false);

                }else{
                    return respond(true);

                }

            });

        } else {
            respond(true);

        }
    },
    msg: '邮箱重复！',
});

filter.add('email', 'trim');
filter.add('email', 'lowercase');



mongooseValidateFilter.validateFilter(UsersSchema, validate, filter);

mongoose.model('User', UsersSchema);


exports.UsersSchema = UsersSchema;
